﻿using ShiQuan.DataRepository;
using ShiQuan.IotDevice.Entity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Linq.Expressions;
using ShiQuan.Utility;

namespace ShiQuan.IotDevice.Business
{
    /// <summary>
    /// 设备检测结果
    /// </summary>
    public class DetectionResultBLL : BaseIotDeviceBLL<DetectionResultEntity>
    {
        /// <summary>
        /// 保存爱德克斯上传的设备数据
        /// </summary>
        /// <param name="model"></param>
        public void SaveAdvics(AdvicsModel model)
        {
            if (string.IsNullOrEmpty(model.yqbh))
            {
                throw new Exception("设备唯一标识不能为空！");
            }
            if(model.details.Count <= 0)
            {
                throw new Exception("检测数据不能为空！");
            }
            IRepository db = new RepositoryFactory().BaseRepository(dbContext).BeginTrans();
            try
            {
                var deviceInstall = db.FindEntity<DeviceInstallEntity>(my => my.SerialNumber == model.yqbh);
                if (deviceInstall == null)
                    throw new Exception("未找到设备安装信息！");

                DetectionResultEntity result = null;
                foreach (var item in model.details)
                {
                    /*2019-12-07 没有哪个数据标识，能够判断是唯一的*/
                    //result = db.FindEntity<DetectionResultEntity>(my => my.RefInstallId == deviceInstall.Id && my.InspectOn == item.jianceriqi && my.SampleCode);
                    DetectionItemEntity testItem = db.FindEntity<DetectionItemEntity>(my => my.Name == item.jiancexiangmu);
                    if(testItem == null)
                    {
                        testItem = new DetectionItemEntity();
                        testItem.Code = DateTime.Now.ToString("yyMMdd-HHmmss");
                        testItem.Name = item.jiancexiangmu;
                        testItem.Id = Guid.NewGuid().ToString();
                        testItem.CreateDate = DateTime.Now;
                        db.Insert<DetectionItemEntity>(testItem);
                    }
                    var sampleId = string.Empty;
                    SampleInfoEntity sampleInfo = db.FindEntity<SampleInfoEntity>(my => my.Name == item.yangpinmingcheng && my.RefCorpId == deviceInstall.RefCorpId);
                    if (sampleInfo == null)
                    {
                        sampleInfo = new SampleInfoEntity();
                        sampleInfo.Id = Guid.NewGuid().ToString();
                        sampleInfo.Code = DateTime.Now.ToString("yyMMdd-HHmmss");
                        sampleInfo.Name = item.yangpinmingcheng;
                        sampleInfo.CreateDate = DateTime.Now;
                        sampleInfo.RefCorpId = deviceInstall.RefCorpId;
                        sampleInfo.CorpName = deviceInstall.CorpName;
                    }
                    else
                        sampleId = sampleInfo.Id;
                    
                    result = new DetectionResultEntity();
                    result.RefInstallId = deviceInstall.Id;
                    result.RefDeviceId = deviceInstall.RefDeviceId;
                    result.DeviceName = deviceInstall.DeviceName;
                    /*检测单位、人、时间信息*/
                    result.RefCorpId = deviceInstall.RefCorpId;
                    result.CorpName = deviceInstall.CorpName;
                    result.InspectBy = item.jianceren;
                    result.InspectOn = item.jianceriqi;
                    if(result.InspectOn != null)
                    {
                        result.Date = result.InspectOn.Value.Date;
                        result.Year = result.InspectOn.Value.Year;
                        result.Month = result.InspectOn.Value.Month;
                        result.Day = result.InspectOn.Value.Day;
                        result.Hour = result.InspectOn.Value.Hour;
                        result.Week = (int)result.InspectOn.Value.DayOfWeek;
                    }
                    result.TestSite = item.jiancedidian;

                    result.RefItemId = testItem.Id;
                    result.TestItem = testItem.Name;
                    result.TestBasis = testItem.TestBasis;
                    result.TestMethod = testItem.TestMethod;

                    result.SampleCode = item.yangpinbianhao;
                    result.RefSampleId = sampleInfo.Id;
                    result.SampleName = sampleInfo.Name;
                    result.BatchCode = string.Empty;

                    result.TestResult = item.jiancejieguo;
                    result.TestValue = item.jiancezhi;

                    result.JudgmentResult = result.TestResult;
                    result.JudgmentStandard = "";

                    result.Id = Guid.NewGuid().ToString();
                    result.CreateDate = DateTime.Now;
                    db.Insert<DetectionResultEntity>(result);

                    /*2019-12-12 侯连文 更新统计样品检测结果*/
                    var list = db.FindList<DetectionResultEntity>(my => my.RefSampleId == sampleInfo.Id);
                    sampleInfo.DetectionCount = list.Count();
                    sampleInfo.QualifiedCount = list.Where(my => my.TestResult == "合格").Count();
                    sampleInfo.UnqualifiedCount = sampleInfo.DetectionCount - sampleInfo.QualifiedCount;
                    if (sampleInfo.DetectionCount > 0)
                    {
                        sampleInfo.QualifiedRate = sampleInfo.QualifiedCount * 1.0m / sampleInfo.DetectionCount;
                        sampleInfo.UnqualifiedRate = sampleInfo.UnqualifiedCount * 1.0m / sampleInfo.DetectionCount;
                    }
                    if (string.IsNullOrEmpty(sampleId))
                    {
                        db.Insert<SampleInfoEntity>(sampleInfo);
                    }
                    else
                        db.Update<SampleInfoEntity>(sampleInfo);
                }
                db.Commit();
            }
            catch(Exception ex)
            {
                db.Rollback();
                throw ex;
            }
            
        }

        protected override Expression<Func<DetectionResultEntity, bool>> QueryStringToExpression(Expression<Func<DetectionResultEntity, bool>> expression, string queryJson)
        {
            if (string.IsNullOrEmpty(queryJson))
                return expression;
            var queryParam = queryJson.ToJObject();
            if (queryParam["RefCorpId"].IsEmpty() == false && queryParam["RefCorpId"].ToString() != "-1")
            {
                var keyword = queryParam["RefCorpId"].ToString();
                expression = expression.And(my => my.RefCorpId == keyword);
            }
            if (queryParam["RefDeviceId"].IsEmpty() == false && queryParam["RefDeviceId"].ToString() != "-1")
            {
                var keyword = queryParam["RefDeviceId"].ToString();
                expression = expression.And(my => my.RefDeviceId == keyword);
            }
            if (queryParam["RefInstallId"].IsEmpty() == false && queryParam["RefInstallId"].ToString() != "-1")
            {
                var keyword = queryParam["RefInstallId"].ToString();
                expression = expression.And(my => my.RefInstallId == keyword);
            }
            if (queryParam["RefItemId"].IsEmpty() == false && queryParam["RefItemId"].ToString() != "-1")
            {
                var keyword = queryParam["RefItemId"].ToString();
                expression = expression.And(my => my.RefItemId == keyword);
            }
            if (queryParam["RefSampleId"].IsEmpty() == false && queryParam["RefSampleId"].ToString() != "-1")
            {
                var keyword = queryParam["RefSampleId"].ToString();
                expression = expression.And(my => my.RefSampleId == keyword);
            }
            if (queryParam["StartDate"].IsEmpty() == false && queryParam["StartDate"].ToString() != "-1")
            {
                var startdate = DateTime.MinValue;
                var keyword = queryParam["StartDate"].ToString();
                DateTime.TryParse(keyword, out startdate);
                if (startdate == DateTime.MinValue)
                    startdate = DateTime.Today;
                expression = expression.And(my => my.Date >= startdate);
            }
            if (queryParam["CloseDate"].IsEmpty() == false && queryParam["CloseDate"].ToString() != "-1")
            {
                var closedate = DateTime.MinValue;
                string keyword = queryParam["CloseDate"].ToString();
                DateTime.TryParse(keyword, out closedate);
                if (closedate == DateTime.MinValue)
                    closedate = DateTime.Today;
                expression = expression.And(my => my.Date <= closedate);
            }
            if (!queryParam["condition"].IsEmpty() && !queryParam["keyword"].IsEmpty())
            {
                string condition = queryParam["condition"].ToString();
                string keyword = queryParam["keyword"].ToString();
                switch (condition)
                {
                    case "InspectBy":
                        {
                            expression = expression.And(my => my.InspectBy.Contains(keyword));
                            break;
                        }
                    case "SampleCode":
                        {
                            expression = expression.And(my => my.SampleCode.Contains(keyword));
                            break;
                        }
                    case "SampleName":
                        {
                            expression = expression.And(my => my.SampleName.Contains(keyword));
                            break;
                        }
                    case "TestItem":
                        {
                            expression = expression.And(my => my.TestItem.Contains(keyword));
                            break;
                        }
                    case "DeviceName":
                        {
                            expression = expression.And(my => my.DeviceName.Contains(keyword));
                            break;
                        }
                    default: break;
                }
            }
            return expression;
        }
    }
}
